// packageF/sachertorte/sachertorteGoods/sachertorteGoods.js
let app = getApp();
let location = require("../../../mybehaviors/location/location");
Page({
  behaviors: [location],
  /**
   * 页面的初始数据
   */
  data: {
    city:'',  //城市名称
    cakeCity:'',
    total:0,
    clicktype:'', //弹窗打开还是关闭
    optionsId:'',
    goodsDetails:{},
    optionsObj:{}, //选中的规格包括活动时间
    timeData: {},
    beginStatus:0, //判断商品状态
    goodsId:'',
    shopList:[],
    iPnoneBottomBol: false,
    specsShow: false, //是否开启规格弹窗
    cakeGoods:{},
    supplyCakeGoods:{},
    getGoods: {},
    groupCode: {}, //群活码
    pluginSetting:{},
    description: '', //自提门店说明
    brand: {
        "id": 179,
        "name": "测试品牌",
        "logo": "1"
    },
    distance:0,
    cakeGoodsOption:[],
    shipAreaType:'',
     // 海报按钮
     btnData2: {
      over_top: 450,
      icon_url: "https://www.yunzmall.com//min_img/bc_eweima.png"
    },
    btnData: {
      over_top: 500,
      icon_url: "https://www.yunzmall.com//min_img/icon-fontclass-zhiding.png"
    },
    showKefu:false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if(options.id) {
      this.setData({
        goodsId: Number(options.id),
        city: options.city,
        cakeCity:  options.city
      })
    }
    
    if (options.scene) { //海报参数
      let scene = decodeURIComponent(options.scene);
      console.log(scene);
      if (scene) {
        var info_arr = [];
        info_arr = scene.split(",");
        for (let i = 0; i < info_arr.length; i++) {
          let chil_arr = [];
          chil_arr = info_arr[i].split("=");
          if (chil_arr[0] == "id") {
            //解决场景：海报带参后字符长度超出，将参数值直接与id合并，通过 / 分割，第一个需为id,其他自定义
            let paramsID = chil_arr[1].split("/");
            console.log(paramsID);
            this.setData({
              goodsId: paramsID[0],
            });
          }else if (chil_arr[0] == "mid") {
            app._setMid(chil_arr[1]);
          } else {
            this.goodsdetails();
          }
        }
      }
    } else {
      if (options.mid) {
        app._setMid(options.mid);
      }
    }
    this.goodsdetails();
    this.getiPnoneBottom();
  },
  goodsdetails() {
    let query = {
      id: this.data.goodsId,
      basic_info:1
    };
    let urlStr = app.getNetAddresss("goods.goods.get-goods-page");
    app._postNetWork({
      url: urlStr,
      data: query,
      success:  (resdata) => {
        let res = resdata.data;
        if (res.result == 1) {
          let getGoods= res.data.get_goods;
          let plugin = res.data?.plugin?.yz_supply_cake;
          let plugin_setting = res.basic_info?.plugin_setting;
          let groupCode = res.data?.plugin?.group_code; //群活码
          let yz_supply_cake_goods = plugin?.data?.yz_supply_cake_goods; //蛋糕叔叔格外的数据
          let goodsOption = yz_supply_cake_goods?.has_many_yz_supply_cake_goods_option[0]; //结束时间处理
          let endTime =  goodsOption?.promotion_end_at || '';
          let _html = getGoods?.content.replace(/<img/g, '<img style="max-width:100%;height:auto;"') ;
          this.endTimeSpecs(goodsOption);
          this.setData({
            getGoods: getGoods,
            pluginSetting: plugin_setting,
            cakeGoods:plugin?.data,
            supplyCakeGoods:yz_supply_cake_goods,
            groupCode:groupCode,
            promotionEndTime: this.endTimeFun(endTime.replace(/-/g,'/')),
            cakeGoodsOption: yz_supply_cake_goods?.has_many_yz_supply_cake_goods_option,
            beginStatus: this.endTimeSpecs(goodsOption),
            optionsObj:getGoods.has_many_options[0],
            'goodsDetails.content': _html,
            customer_open: res.data.customer_service?.customer_open == "1" ? true : false,
            cservice: res.data.customer_service?.cservice,
            service_QRcode: res.data.customer_service?.service_QRcode,
            service_mobile: res.data.customer_service?.service_mobile,
          })
          if (plugin_setting?.yz_supply_cake?.is_ios_sell === 1 || plugin_setting?.yz_supply_cake?.is_ios_sell === "1") {
            // 卡券商品 并开启 IOS禁用
            if (app.isIosOrAndroid() === "ios") {
              this.setData({
                beginStatus: -1
              })
            }
            wx.getSystemInfo({ //加ios判断
              success:(res) => {
                if(res.system.indexOf('iOS') > -1) {
                  this.setData({
                    beginStatus: -1
                  })
                }
              }
            })
          }
        } else {
          wx.showModal({
            content: res.msg,
            success (res) {
              if (res.confirm) {
                wx.navigateBack({
                  delta: 1
                })
              }
            }
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  endTimeFun(endTime){
    let date = new Date(endTime);
    let timeDate = date.getTime();
    let current = new Date().getTime();
    return timeDate - current;
  },
  getRule() {
    let query = {
      city:this.data.cakeCity,
      goods_id: this.data.goodsId
    };
    let urlStr = app.getNetAddresss("plugin.yz-supply-cake.frontend.index.index.getRule");
    app._getNetWork({
      url: urlStr,
      data:query,
      success: (resdata) => {
        let res = resdata.data
        if (res.result == 1) {
          if(res.data.code !== 200) {
            wx.showToast({
              icon: 'none',
              title: res.data.msg,
              duration: 1500
            });
            this.setData({
              description:res.data.msg,
            })
            return;
          }
          let data = res.data;
          this.setData({
            description:data.data?.description,
            shipAreaType:data.data?.ship_area_type,
            shopList: data.data?.shop,
          })
          if(this.data.shipAreaType === '2' || this.data.shipAreaType === 2) {//门店半径区域)
            let shipRule = JSON.parse(data.data?.ship_rule) || {};
            let nonDefault = shipRule.non_default || {}; 
            let distance = '';
            for(let key in nonDefault) {
              console.log(key);
              distance = nonDefault[key].distance;
            }
            this.setData({
              distance: distance * 1000,
            })
          }
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  deliveryClick() { //跳转配送范围
    wx.navigateTo({
      url: `/packageF/sachertorte/deliveryArea/deliveryArea?goodsId=${this.data.goodsId}&city=${this.data.cakeCity}`,
    })
  },
  imgH(e){
    var winWid = wx.getSystemInfoSync().windowWidth;//获取当前屏幕的宽度
    var imgh=e.detail.height;//图片高度
    var imgw=e.detail.width;
    var swiperH=winWid*imgh/imgw + "px"　//等比设置swiper的高度。  即 屏幕宽度 / swiper高度 = 图片宽度 / 图片高度    ==》swiper高度 = 屏幕宽度 * 图片高度 / 图片宽度
    this.setData({
        Hei:swiperH//设置高度
    })
  },
  onTimeChange(e) {
    this.setData({
      timeData: e.detail,
    });
  },
  gotoMember() { //跳转会员中心
    wx.reLaunch({
      url: "/packageG/member_v2/member_v2",
    });
  },
  //海报生成
  postShow(e) {
    this.setData({
      posterShow: true,
      showSahre: false,
    });
  },
  posterClick() {
    this.setData({
      posterShow: true,
    });
  },
  posterClose() {
    this.setData({
      posterShow: false,
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    try {
      this._getLocation((mapdata, e) => { //获取定位的城市，拿到定位的信息
        let city = mapdata.address_component.city;
        if(!this.data.cakeCity) {
          this.setData({
            cakeCity:city
          });
        }
        //定位后调用首页接口和推荐列表接口
        this.getRule();
      });
    } catch (e) {
      console.log(e);
      this.getRule();
    }
  },
  getiPnoneBottom() {
    try {
      var value = wx.getStorageSync("iPhoneBottom");
      if (value) {
        this.setData({
          iPnoneBottomBol: true,
        });
      }
    } catch (e) {}
  },

  onService() { //点赞功能
   this.setData({
    showKefu:true
   })
  },
  onIndex() { //跳转首页
    wx.navigateTo({
      url: '/packageF/sachertorte/sachertorteIndex/sachertorteIndex',
    })
  },
  specificationOn() {
    this.setData({
      specsShow: true
    })
  },
  cakeGoodsBuy() {
    this.setData({
      specsShow: true
    })
  },
  backOn() {
    wx.navigateBack({
      delta: 1
    })
  },
  toGroupCode() { //群活码跳转功能
    if(this.data.groupCode.jump_mode === 'home') {
      wx.reLaunch({
        url: '/packageE/groupCode/groupCode',
      });
    }else if(this.data.groupCode.code_mini_url){
      wx.navigateTo({
        url: this.data.groupCode.code_mini_url
      });
    }
  },
  close_yz_specs_popup(e) {
    this.setData({
      specsShow: false,
    });

  },
  selectSpecsOn(e) { //获取规格弹窗的数据是否显示可购买
    let {clicktype,goodsCount,optionsId} = e.detail;
    let optionItem = this.data.cakeGoodsOption.find((item,index) => {
      return item.option_id === optionsId
    })
    let optionsObj = this.data.getGoods?.has_many_options.find((item,index) => { //显示规格文字
      return item.id === optionsId
    })
    let endTime = this.endTimeFun(optionItem?.promotion_end_at || '') || '';
    this.setData({
      optionsObj: optionsObj, //选中的规格
      clicktype:clicktype,
      total:goodsCount,
      optionsId: optionsId,
      beginStatus: this.endTimeSpecs(optionItem),
      promotionEndTime: endTime
    });
    if(goodsCount === 0) {
      this.setData({
        beginStatus:-1
      })
    }
    console.log('1111111111');
    console.log(this.data.pluginSetting?.yz_supply_cake?.is_ios_sell);
    if (this.data.pluginSetting?.yz_supply_cake?.is_ios_sell === 1 || this.data.pluginSetting?.yz_supply_cake?.is_ios_sell === "1") {
      // 卡券商品 并开启 IOS禁用
      if (app.isIosOrAndroid() === "ios") {
        this.setData({
          beginStatus: -1
        })
      }
      
      wx.getSystemInfo({ //加ios判断
        success:(res) => {
          if(res.system.indexOf('iOS') > -1) {
            this.setData({
              beginStatus: -1
            })
            console.log(this.data.beginStatus);
          }
        }
      })
    }
  },
  submitAction() {
    if (this.data.getGoods.has_option == 1 && !this.data.optionsId) {
      wx.showToast({
        icon: 'none',
        title: '规格id不可为空，请选择规格！',
        duration: 1500
      });
      return;
    }
    if (this.data.clicktype === 1) {
      //点击确认按钮
      this.setData({
        specsShow: false,
      });
      let url = '/packageD/buy/myOrder_v2/myOrder_v2?tag=cake';
      let _urlParam = `&goodsId=${this.data.goodsId}&optionsId=${this.data.optionsId}&total=${this.data.total}&city=${this.data.cakeCity}`;
      wx.navigateTo({
        url: url + _urlParam
      });
    } else {
      this.setData({
        specsShow: false,
      });
    }
  },
  endTimeSpecs(ootionItem) {
    let endTime = ootionItem?.promotion_end_at; //结束时间处理 
    let beginStatus = '';
    if(endTime) { //默认可能会没有时间常数
      let date = new Date(endTime.replace(/-/g,'/'));
      let current = new Date().getTime();
      if(date > current) {
        beginStatus = 2;
      }
    }
    return beginStatus;
  },
  brandNav(event) {
    let brandId = event.currentTarget.dataset.brandid;
    wx.navigateTo({
      url: `/packageF/sachertorte/classify/classify?brandId=${brandId}&city=${this.data.cakeCity}`,
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let shareConfig = {
      title: this.data.getGoods.title,
      path: `/packageF/sachertorte/sachertorteGoods/sachertorteGoods?id=${this.data.goodsId}`,
      imageUrl: this.data.getGoods?.thumb_url[0]
    }
    return {
      title: shareConfig.title,
      path: shareConfig.path,
      imageUrl: shareConfig.imgUrl
    };
  }
})